$(document).ready( function() {
	// als de localstorage een username en wachtwoord heeft verifeer dit tegen de webservice
	if( getUsername() != null && getPassword() != null ) {
		checkStoredLogin( getUsername(), getPassword() );
	}
	
	window.setInterval(refreshPlayerList, 1000);
	
	$('#headerText').html('Saxion Roulette Table ' + getVarFromUrl('tableId') );
});

function refreshPlayerList() {
	$.getJSON('http://localhost:8080/WT_Roulette/rest/table/' + getVarFromUrl('tableId'), function(data) {
		var players = data['players'];
		var bets = data['bets'];
		var tableString = "<tr><th width='100px'>Player name</th><th width='100px'>Stack</th><th width='100px'>Last Bet</th></tr>";
		
		if( bets != null ) {
			for( var i = 0; i<players.length; i++ ) {
				tableString += "<tr><td>" + players[i].username + "</td><td>" + players[i].amountOfCash + "</td><td>" + bets[i].cashAmount + "</td></tr>";
				
				//Update ook het login gedeelte
				if( players[i].username == getUsername() ) {
					buildLoggedOnText( getUsername(), players[i].amountOfCash );
				}
			}
			$('#playerTable').html(tableString);
		}
	});
}

function checkStoredLogin( username, password ) {
	$.getJSON('http://localhost:8080/WT_Roulette/rest/lobby/login?username=' + username + "&password=" + password, function(data) {
		var username = data["username"];
		var cash = data['amountOfCash'];
		if( username != null && cash != null ) {
			buildLoggedOnText( username, cash );
			$('#login').hide();
			$('#loggedOn').show();
		} else {
			alert( 'Failed to log in, please try again' );
			logout();
		}
	});
}

function buildLoggedOnText(username, cash){
	var loggedOnText = "Username: " + username + "<br/>Cash: " + cash + "<br/>";
	var leaveTable = "<button onClick='leaveTable()' id='leaveTableButton'>Leave Table</button>";
	
	$('#loggedOn').html(loggedOnText + leaveTable);
}

function leaveTable() {
	// Delete is niet volledig RESTful webservice
	// De delete methode is idempotent, het verplicht dat de server een status 200(OK) teruggeeft zelfs als de server de resource heeft verwijderd bij een vorig request..
	$.ajax({
		type: 'DELETE',
		url: 'http://localhost:8080/WT_Roulette/rest/table/' + getVarFromUrl('tableId') + "/" + getId(),
		succes: returnBackToLobby(),
		error: function(result, ajaxOptions, thrownError) {
			alert("Errormessage: " + result.status);
			alert(thrownError);
		}
	});
}

function returnBackToLobby() {
	window.location.href = "index.html";
}

function makeBet(color) {	
	if( $('#betAmount').val() === '' ) {
		alert('Vul een bedrag in!');
		return;
	}
	
	var jsonObject = new Object();
	jsonObject['playerId'] = getId();
	jsonObject['cashAmount'] = $('#betAmount').val();
	if( color === 'Black' ) {
		jsonObject['isBlack'] = true;
	} else {
		jsonObject['isBlack'] = false;
	}
	var jsonString = JSON.stringify( jsonObject );
	
	$.ajax({
		type: 'POST',
		url: 'http://localhost:8080/WT_Roulette/rest/table/' + getVarFromUrl('tableId'),
		dataType: 'json',
		contentType: 'application/json; charset=utf-8',
		data: jsonString,
		succes: function(result){
			
		},
		error: function(result, ajaxOptions, thrownError) {
			alert("Errormessage: " + result.status);
			alert(thrownError);
		}
	});
	
}

function getVarFromUrl (varName ) {
	// Deze methode parsed de url en geeft de waarde terug die hoort bij de variable naam
	searchString = document.location.search;         
	returnValue = '';
	
	// Loop om alle waardes van de variablen op te krijgen.
	do {
		varNameIndex = searchString.indexOf(name + '=');
		
		if(varNameIndex != -1) {
			searchString = searchString.substr(varNameIndex + name.length + 1, searchString.length - varNameIndex);		     
		    endValue = searchString.indexOf('&');
		    
		    if(endValue != -1) {
		    	value = searchString.substr(0, endValue); 
		    } else {
		    	value = searchString; 
		    }                
		     
		    if(returnValue == '' || value == '') {
		    	returnValue += value;
		    } else {
		    	returnValue += ', ' + value;
		    }
		}
	 } while(varNameIndex != -1)
	   
	// verwijder eventuele spaties
	space = returnValue.indexOf('+');
	while(space != -1) {
		returnValue = returnValue.substr(0, space) + ' ' + 
	    returnValue.substr(space + 1, returnValue.length);
	                                                
	    space = returnValue.indexOf('+');
	}
	return(returnValue);
}

